package org.itboys.fuzion.service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.itboys.fuzion.entity.MemberTwoCodeMedia;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.seller.entity.Seller;
import org.itboys.seller.service.SellerService;
import org.itboys.weixin.entity.WeixinConfig;
import org.itboys.weixin.service.WeixinConfigService;
import org.itboys.weixin.tools.HttpHelper;
import org.itboys.weixin.tools.WeixinUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;

/**
 * 商店  + 会员 上传的素材mediaId值记录
 * @author Administrator
 *
 */
@Service
public class MemberTwoCodeMediaService extends BaseService<MemberTwoCodeMedia, Long>{
	
	private static final long serialVersionUID = -1090901102986504527L;
	
	private final static String WEIXIN_DELETE_MEDIAID = "https://api.weixin.qq.com/cgi-bin/material/del_material?access_token=";
	
	@Autowired
	private SellerService sellerService;
	@Autowired
	private WeixinConfigService weixinConfigService;
	
	@Resource(name="baseMongoDS")
	private MongoDataSource ds;

	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}

	
	/**
	 * 根据sellerId和memberId查询记录值
	 * 
	 * @param conditions
	 * @param number
	 */
	public MemberTwoCodeMedia list(Long sellerId, Long memberId){
		Map<String, Object> param = Maps.newHashMapWithExpectedSize(2);
		param.put("sellerId", sellerId);
		param.put("memberId", memberId);
		List<MemberTwoCodeMedia> list = super.list(param);
		return (list != null && list.size() > 0) ? list.get(0) : null;
	}
	
	/**
	 * 清除某一个店铺下的所有素材记录
	 * @param shopId
	 */
	public void cleanMediaIdByShopId(Long sellerId){
		
		Seller seller = sellerService.getById(sellerId);
		WeixinConfig wc = weixinConfigService.getById(seller.getWeixinId());
		
		String appid = wc.getAppId();
		String secret = wc.getAppSecret();
		String access_token =WeixinUtils.getAccessToken(appid, secret);//从缓存中获取token
		
		List<MemberTwoCodeMedia> list = super.findByField("sellerId", sellerId);
		
		Map<String, Object> param = Maps.newHashMapWithExpectedSize(1);
		list.forEach(sm -> {
			if(!StringUtils.isBlank(sm.getMediaId())){
				param.put("media_id", sm.getMediaId());
				try{
					deleteMediaThread(WEIXIN_DELETE_MEDIAID + access_token, param, sm.getId());
				}catch(Exception e){
					e.printStackTrace();
					logger.error("除某一个店铺下的所有素材记录失败，建议再清除一次", e);
				}
			}
		});
	}
	
	/**
	 * 开一个线程  用来删除微信平台上的素材
	 * @param url
	 * @param param
	 */
	private void deleteMediaThread(String url, Map<String, Object> param, Long id){
		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(6);
		fixedThreadPool.execute(new Runnable(){
			@Override
			public void run() {
				String result = HttpHelper.doPost(url, param);
				if(!StringUtils.equals(result, HttpHelper.FAIL)){//如果请求微信删除素材成功  就将本地数据库中的记录删除
					getMongoDataSource().delete(id);
				}
			}
		});
	}

}
